'''
自定义返回处理
'''

# 导入控制返回的JSON格式的类
from rest_framework.renderers import JSONRenderer


class MyRender(JSONRenderer):
    # 重构render方法
    def render(self, data, accepted_media_type=None, renderer_context=None):
        if renderer_context:
            response = renderer_context['response']
            code = 0 if int(response.status_code / 100) == 2 else response.status_code
            msg = 'success'
            if isinstance(data, dict):
                msg = data.pop('msg', msg)
                code = data.pop('code', code)
                data = data.pop('data', data)
            if code != 0 and data:
                msg = data.pop('detail', 'failed')
            response.status_code = 200
            res = {
                'code': code,
                'msg': msg,
                'data': data,
            }
            print(res)
            return super().render(res, accepted_media_type, renderer_context)
        else:
            return super().render(data, accepted_media_type, renderer_context)

        # if renderer_context:
        #     if isinstance(data, dict):
        #         msg = data.pop('msg', 'success')
        #         code = data.pop('code', 0)
        #         data = data.pop('data', data)
        #         if isinstance(data, list):
        #             data = {
        #                 'total': len(data),
        #                 'data': data
        #             }
        #     elif isinstance(data, list):
        #         msg = '成功'
        #         code = 0
        #         data = {
        #             'total': len(data),
        #             'data': data
        #         }
        #     else:
        #         msg = 'success'
        #         code = 0
        #
        #     # 重新构建返回的JSON字典
        #     for key in data:
        #         # 判断是否有自定义的异常的字段
        #         if key == 'message':
        #             msg = data[key]
        #             data = ''
        #             code = 1
        #
        #     ret = {
        #         'msg': msg,
        #         'code': code,
        #         'data': data,
        #     }
        #     # 返回JSON数据
        #     return super().render(ret, accepted_media_type, renderer_context)
        # else:
        #     return super().render(data, accepted_media_type, renderer_context)

